<?php
namespace Home\Controller;
use MyBase\BaseController;
class IndexController extends BaseController {
    public function index(){
        //取出存储的用户信息
        if(cookie("USER")){
            $this->assign("user_remembered",cookie('USER'));
        } 
        //查询节日食品，食品（id=3）
        $foodColumns = array(
            'goods_id',
            'goods_name',
            'goods_content',
            'goods_price',
            'goods_uprice',
            'goods_pic',
            'goods_add_time',
            'goods_recomment'
        );
        $holidayFoodData = $this->GoodsModel->getGoodsByCondition(array('goods_type'=>3),$foodColumns,array('goods_add_time'=>'desc'));
        foreach ($holidayFoodData as $k => $v) {
           $holidayPicArr = json_decode($holidayFoodData[$k]['goods_pic'],true);
        
            foreach ($holidayPicArr as $key => $value) {
                $holidayPicArr[$key] =  __ROOT__.'/Uploads/food/'.$holidayFoodData[$k]['goods_add_time'].$holidayFoodData[$k]['goods_id'].'/'.$value;
            } 
            $holidayFoodData[$k]['goods_pic'] = $holidayPicArr;
        }
        $this->assign('holidayFoodData',$holidayFoodData);
        //查询儿童食品，儿童（id=1）
        $childFoodData = $this->GoodsModel->getGoodsByCondition(array('goods_type'=>1),$foodColumns,array('goods_add_time'=>'desc'));
        foreach ($childFoodData as $k => $v) {
            $childFoodData[$k]['goods_pic'] = $this->formatFoodPic($childFoodData[$k]['goods_pic'],$v,true);
        }
        $this->assign('childFoodData',$childFoodData);
        //查询四季食品，儿童（id=2）
        $seasonFoodData = $this->GoodsModel->getGoodsByCondition(array('goods_type'=>2),$foodColumns,array('goods_add_time'=>'desc'));
        foreach ($seasonFoodData as $k => $v) {
            $seasonFoodData[$k]['goods_pic'] = $this->formatFoodPic($seasonFoodData[$k]['goods_pic'],$v,true);
        }
        $this->assign('seasonFoodData',$seasonFoodData);

        //合作加盟的数据
        $joinData = $this->JoinModel->getJoinList(0,3);
        $this->assign('joinData',$joinData);

        //节日推荐
        $holidayFoodRec = $this->GoodsModel->getGoodsByCondition(array('goods_type'=>3,'goods_recomment'=>'Y'),$foodColumns,array('goods_add_time'=>'desc'),5);
        foreach ($holidayFoodRec as $k => $v) {
            $holidayFoodRec[$k]['goods_pic'] = $this->formatFoodPic($holidayFoodRec[$k]['goods_pic'],$v,true);
        }
        $this->assign('holidayFoodRec',$holidayFoodRec);

        //四季推荐
        $seasonFoodRec = $this->GoodsModel->getGoodsByCondition(array('goods_type'=>2,'goods_recomment'=>'Y'),$foodColumns,array('goods_add_time'=>'desc'),5);
        foreach ($seasonFoodRec as $k => $v) {
            $seasonFoodRec[$k]['goods_pic'] = $this->formatFoodPic($seasonFoodRec[$k]['goods_pic'],$v,true);
        }
        $this->assign('seasonFoodRec',$seasonFoodRec);
        //儿童推荐
        $childFoodRec = $this->GoodsModel->getGoodsByCondition(array('goods_type'=>1,'goods_recomment'=>'Y'),$foodColumns,array('goods_add_time'=>'desc'),5);
        foreach ($childFoodRec as $k => $v) {
            $childFoodRec[$k]['goods_pic'] = $this->formatFoodPic($childFoodRec[$k]['goods_pic'],$v,true);
        }
        $this->assign('childFoodRec',$childFoodRec);

        //我的节日
        $holidayFoodMy = $this->GoodsModel->getGoodsByCondition(array('goods_type'=>3,'goods_recomment'=>'Y'),$foodColumns,array('goods_pv'=>'desc'),5);
        foreach ($holidayFoodMy as $k => $v) {
            $holidayFoodMy[$k]['goods_pic'] = $this->formatFoodPic($holidayFoodMy[$k]['goods_pic'],$v,true);
        }
        $this->assign('holidayFoodMy',$holidayFoodMy);      

        //我的四季
        $seasonFoodMy = $this->GoodsModel->getGoodsByCondition(array('goods_type'=>2,'goods_recomment'=>'Y'),$foodColumns,array('goods_pv'=>'desc'),5);
        foreach ($seasonFoodMy as $k => $v) {
            $seasonFoodMy[$k]['goods_pic'] = $this->formatFoodPic($seasonFoodMy[$k]['goods_pic'],$v,true);
        }
        $this->assign('seasonFoodMy',$seasonFoodMy); 

        //我的童年
        $childFoodMy = $this->GoodsModel->getGoodsByCondition(array('goods_type'=>1,'goods_recomment'=>'Y'),$foodColumns,array('goods_pv'=>'desc'),5);
        foreach ($childFoodMy as $k => $v) {
            $childFoodMy[$k]['goods_pic'] = $this->formatFoodPic($childFoodMy[$k]['goods_pic'],$v,true);
        }
        $this->assign('childFoodMy',$childFoodMy);

        // 佳味菜肴
        $cookbookColumns = array('cookbook_id','cookbook_name','cookbook_content','cookbook_photo','cookbook_add_time','cookbook_description','cookbook_pv','cookbook_good','cookbook_bad');
        $cookbookData = $this->CookBookModel->getCookbookByCondition(array('cookbook_status'=>'Y'),$cookbookColumns,array('cookbook_add_time'=>'desc'));
        foreach ($cookbookData as $key => $value) {
           $cookbookData[$key]['cookbook_photo'] =  __ROOT__.'/Uploads/cookbook/'.$value['cookbook_add_time'].$value['cookbook_id'].'/'.$value['cookbook_photo'];
        }
        $this->assign('cookbookData',$cookbookData);

        //精品菜式
        $cookbookJData = $this->CookBookModel->getCookbookByCondition(array('cookbook_status'=>'Y'),$cookbookColumns,array('cookbook_pv'=>'desc'));
        foreach ($cookbookJData as $key => $value) {
           $cookbookJData[$key]['cookbook_photo'] =  __ROOT__.'/Uploads/cookbook/'.$value['cookbook_add_time'].$value['cookbook_id'].'/'.$value['cookbook_photo'];
        }
        $this->assign('cookbookJData',$cookbookJData);       

        $this->assign('myCarNum',$this->carNum);
        //position
        $this->assign('position',array(__CONTROLLER__=>'首页'));
    	$this->display();
    }
    /**
     * [formatFoodPic 格式化图片信息]
     * @param  [type]  $PicJson [存储图片的json串]
     * @param  [type]  $v       [一条记录的信息]
     * @param  boolean $flag    [是否只选中一个文件就终止]
     * @return [type]           
     */
    public function formatFoodPic($PicJson,$v,$flag=false){
        $PicArr = json_decode($PicJson,true);
        foreach ($PicArr as $key => $value) {
            if($unsetFlag){
                unset($PicArr[$key]);
            }else{
                $PicArr[$key] =  __ROOT__.'/Uploads/food/'.$v['goods_add_time'].$v['goods_id'].'/'.$value;
                $onePic = __ROOT__.'/Uploads/food/'.$v['goods_add_time'].$v['goods_id'].'/'.$value;
            }
            if($flag){
                $unsetFlag = true;
            }
        } 
        if($flag){
            return $onePic;
        }else{
            return $PicArr;  
        }
        
    }
    public function foodList(){
        $getData = I("get.");
        $goodsData = $this->GoodsModel->getGoodsByCondition(array('goods_status'=>'Y','goods_type'=>$getData['type']),"*",array('goods_add_time'=>'DESC'),6,1);
        
        foreach ($goodsData as $k => $v) {
            $goodsData[$k]['goods_pic'] = $this->formatFoodPic($goodsData[$k]['goods_pic'],$v,true);
        }
        $this->assign('goodsData',$goodsData);
        $this->assign('goodsPage',1+1);    
        $this->assign('goodsType',$getData['type']);    
        //最近热卖
        $hotColumns = array('goods_id','goods_name','goods_pv');
        $recenterHot = $this->GoodsModel->getGoodsByCondition(array('goods_status'=>'Y'),$hotColumns,array('goods_add_time'=>'DESC'),9);
        $this->assign('recenterHot',$recenterHot);
        $scanfData = $this->getLatestScanf();
        $this->assign('scanfData',$scanfData);

        $this->assign('myCarNum',$this->carNum);
        $this->display();
    }
    public function cookbookList(){
        $cookbookColumns = array('cookbook_id','cookbook_name','cookbook_description','cookbook_photo','cookbook_good','cookbook_bad','cookbook_add_time');
        $cookbookData = $this->CookBookModel->getCookbookByCondition(array('cookbook_status'=>'Y'),$cookbookColumns,array('cookbook_add_time'=>'DESC'),9,1);
        
        foreach ($cookbookData as $key => $value) {
           $cookbookData[$key]['cookbook_photo'] = __ROOT__.'/Uploads/cookbook/'.$value['cookbook_add_time'].$value['cookbook_id'].'/'.$value['cookbook_photo'];
        }
        $this->assign('cookbookData',$cookbookData);
        $this->assign('cookbookPage',1+1);
        // print_r($cookbookData);
        //最近热卖
        $hotColumns = array('goods_id','goods_name','goods_pv');
        $recenterHot = $this->GoodsModel->getGoodsByCondition(array('goods_status'=>'Y'),$hotColumns,array('goods_add_time'=>'DESC'),9);
        $this->assign('recenterHot',$recenterHot);
        $scanfData = $this->getLatestScanf();
        $this->assign('scanfData',$scanfData);
        $this->display();       
    }
    public function getLatestScanf(){
        $scanfData = cookie('latestData');
        if(isset($scanfData) && !empty($scanfData)){
            $scanfDataArr = unserialize($scanfData);
            $scanfDataRes = $this->GoodsModel->getGoodsInfoById($scanfDataArr);
        }else{
            $scanfDataRes = array();
        }
        return $scanfDataRes;
    }
    //将访问的数据存入最近浏览中
    private function writeLatestScanf($foodId){
        $latestOld = array();
        //如果COOKIE[''myproduct]存在需要保留里面的值
        $latest = cookie('latestData');
        if(isset($latest)){
            if(!empty($latest)){
                $latestOld = unserialize($latest);
                if(!in_array($foodId,$latestOld)){
                    if(count($latestOld) >= 10){//当数量已经大于等于10时   去掉数组中的一个数后再添加
                        array_shift($latestOld);
                    } 
                }else{
                    return;
                }
            }
        }
        if(!empty($foodId)){
            $latestOld[] = $foodId;
            cookie('latestData',serialize($latestOld),time()+3600*24);
        }
    }
	//获取一次请求的数据
    public function getMore(){
        for ($i=0;$i<6;$i++){
            $res[$i] = rand(170, 170);
        }
        print_r($res);
        $this->ajaxReturn(true,'获取列表成功！',$res);
    }
    public function cookbookGetMore(){
        $getData = I("get.");
        $cookbookColumns = array('cookbook_id','cookbook_name','cookbook_description','cookbook_photo','cookbook_good','cookbook_bad','cookbook_add_time');
        $cookbookData = $this->CookBookModel->getCookbookByCondition(array('cookbook_status'=>'Y'),$cookbookColumns,array('cookbook_add_time'=>'DESC'),9,$getData['pageNum']);
        foreach ($cookbookData as $key => $value) {
           $cookbookData[$key]['cookbook_photo'] = $value['cookbook_add_time'].$value['cookbook_id'].'/'.$value['cookbook_photo'];
        }
        //把图片保存目录传过去
        $picBaseDir = __ROOT__.'/Uploads/cookbook/';
        if(count($cookbookData) > 0){
            $this->ajaxReturn(true,'获取列表成功',
                array(
                    'data'      =>  $cookbookData,
                    'dir'       =>  $picBaseDir,
                    'pageNum'   =>  $getData['pageNum']+1
                    )
            );
        }else{
            $this->ajaxReturn(false,'没有数据了');
        }
    }
    //商品更多
    public function foodGetMore(){
        $getData = I("get.");
        $goodsData = $this->GoodsModel->getGoodsByCondition(array('goods_status'=>'Y','goods_type'=>$getData['goodsType']),"*",array('goods_add_time'=>'DESC'),6,$getData['pageNum']);
        foreach ($goodsData as $k => $v) {
            $goodsData[$k]['goods_pic'] = $this->formatFoodPic($goodsData[$k]['goods_pic'],$v,true);
        }
        if(count($goodsData) > 0){
            $this->ajaxReturn(true,'获取列表成功',
                array(
                    'data'      =>  $goodsData,
                    'pageNum'   =>  $getData['pageNum']+1
                    )
            );
        }else{
            $this->ajaxReturn(false,'没有数据了');
        }        
         
    }
    //商品细节
    public function foodDetail(){
        //得到商品id，在url上
        $getData = I("get.");
        $foodId = $getData['food_id'];
        //写入最近浏览
        $this->writeLatestScanf($foodId);
        $foodInfo =$this->GoodsModel->getGoodsInfoById($foodId);
        $foodPic = json_decode($foodInfo[0]['goods_pic'],true);
        foreach ($foodPic as $key => $value) {
           $foodPic[$key] =  __ROOT__.'/Uploads/food/'.$foodInfo[0]['goods_add_time'].$foodInfo[0]['goods_id'].'/'.$value;
        }
        $foodInfo[0]['goods_pic'] = $foodPic;
        $this->assign('food_info',$foodInfo[0]);
        $this->assign('myCarNum',$this->carNum);
        //position
        $this->assign('position',array(__CONTROLLER__=>'首页',"#" =>'商品详细'));
        $this->display();
    }
    //菜谱详细
    public function cookbookDetail(){

        $getData = I('get.');
        $cookbookInfo = $this->CookBookModel->getCookbookInfoById($getData['cookbook_id']);
        if(!$cookbookInfo){
            $this->redirect("Index/cookbookList");
        }
        $cookbookInfo['cookbook_photo'] = __ROOT__.'/Uploads/cookbook/'.$cookbookInfo['cookbook_add_time'].$cookbookInfo['cookbook_id'].'/'.$cookbookInfo['cookbook_photo'];
        $cookbookInfo['cookbook_content'] = 
        $this->assign('cookbookInfo',$cookbookInfo);
        //最近热卖
        $hotColumns = array('goods_id','goods_name','goods_pv');
        $recenterHot = $this->GoodsModel->getGoodsByCondition(array('goods_status'=>'Y'),$hotColumns,array('goods_add_time'=>'DESC'),9);
        $this->assign('recenterHot',$recenterHot);
        $scanfData = $this->getLatestScanf();
        $this->assign('scanfData',$scanfData);
        $this->assign('myCarNum',$this->carNum);
        $this->assign('position',array(__CONTROLLER__=>'首页',"#" =>'菜谱详细'));
        $this->display("Index/cookbookdetail");
    }
    public function joinUs(){

        $joinAll = $this->JoinModel->getJoinAll();
        foreach ($joinAll as $key => $value) {
            $joinAll[$key]['join_logo'] =  __ROOT__.'/Uploads/join/'. $joinAll[$key]['join_date']. $joinAll[$key]['join_id'].'/'.$joinAll[$key]['join_logo'];
        }
        $this->assign('join_data',$joinAll);
        $this->assign('myCarNum',$this->carNum);
        $this->assign('position',array(__ACTION__ =>'合作加盟'));
        $this->display("joinus");
    }
    public function aboutUs(){
        $aboutUs = $this->AboutModel->getAboutUsData();
        $aboutUs = htmlspecialchars_decode($aboutUs['about_content']);
        $this->assign('about_us',$aboutUs);
        $this->assign('myCarNum',$this->carNum);
        $this->assign('position',array(__ACTION__ =>'关于我们'));
        $this->display("aboutus");
    }


    //添加到购物车
    public function foodAddToCar(){
        $postData = I('post.');
        $arrOld = array();
        //如果COOKIE['myCar']存在需要保留里面的值
        $cookieData = cookie('myCar');
        if(isset($cookieData)){
            if(!empty($cookieData)){
                $arrOld = unserialize($cookieData);
            }
        }
        if(!empty($postData['goods_id']) && !empty($postData['goods_num'])){
            $arrOld[$postData['goods_id']] = $postData['goods_num'];
            // print_r($postData);
            $res = setcookie('myCar',serialize($arrOld),time()+3600*24,'/');
            if($res){
                $this->ajaxReturn(true,'成功加入购物车！');
            }else{
                $this->ajaxReturn(false,'加入失败！');
            }   
        }
    }

    //我的购物车
    public function myCar(){
        $carData = cookie('myCar');
        $carDataArr = unserialize(cookie('myCar'));
        //获取cookie中的值
        $goodsIdArr = array();
        foreach ($carDataArr as $key => $value) {
            array_push($goodsIdArr, $key);
        }
        $goodsDataArr = $this->GoodsModel->getGoodsInfoById($goodsIdArr);
        //准备前段显示的数据
        $goodsTotalPrice = 0;//平民总价
        $goodsTotalUPrice = 0;//会员总价
        foreach ($goodsDataArr as $k => $v) {
            $goodsTotalPrice += $v['goods_price']*$carDataArr[$v['goods_id']]; 
            $goodsTotalUPrice += $v['goods_uprice']*$carDataArr[$v['goods_id']];
            $carDataPicArr = json_decode($goodsDataArr[$k]['goods_pic'],true);
            $showPic = array();//为了只显示一个图片
            foreach ($carDataPicArr as $key => $value) {
                 $showPic[$key] =  __ROOT__.'/Uploads/food/'.$v['goods_add_time'].$v['goods_id'].'/'.$value;
                break;
            }
            $goodsDataArr[$k]['goods_pic'] = $showPic; 
            $goodsDataArr[$k]['goods_num'] = $carDataArr[$v['goods_id']];
        }
        // print_r($goodsDataArr);
        $this->assign('carDataArr',$goodsDataArr);
        $this->assign('goodsTotalPrice',$goodsTotalPrice);//平民总价
        $this->assign('goodsTotalUPrice',$goodsTotalUPrice);//会员总价
        $this->assign('goodsDiffer',$goodsTotalPrice-$goodsTotalUPrice);//差价
        //购物车中商品的数量
        //在没有设置myCar的时候为什么count(unserialize(cookie('myCar'))) 为 1
        $this->assign('myCarNum', $this->carNum);
        $this->assign('position',array(__ACTION__ =>'我的购物车'));
        $this->display('Index/mycar');
    }

    //清空购物车
    public function cleanMyCar(){
        cookie('myCar',null);
        $this->ajaxReturn(true,'清除购物车成功！');
    }
    //改变购物车商品的数量
    public function changeMyCarNum(){
         $carData = cookie('myCar');
         $carDataArr = unserialize($carData);
         $postData = I('post.');
         $postData[$postData['food_id']] = $postData['food_num'];
         unset($postData['food_id']);
         unset($postData['food_num']);
         foreach ($postData as $key => $value) {
             $carDataArr[$key] = $value;
         }
         cookie('myCar',serialize($carDataArr));
        $goodsIdArr = array();
        foreach ($carDataArr as $key => $value) {
            array_push($goodsIdArr, $key);
        }
        $goodsDataArr = $this->GoodsModel->getGoodsInfoById($goodsIdArr);
        
        //准备前段显示的数据
        $goodsTotalPrice = 0;//平民总价
        $goodsTotalUPrice = 0;//会员总价
        foreach ($goodsDataArr as $k => $v) {
            $goodsTotalPrice += $v['goods_price']*$carDataArr[$v['goods_id']]; 
            $goodsTotalUPrice += $v['goods_uprice']*$carDataArr[$v['goods_id']];
        }
        $returnArr = array(
            'goodsTotalPrice' => $goodsTotalPrice,
            'goodsTotalUPrice' => $goodsTotalUPrice,
            'goodsDiffer' => $goodsTotalPrice-$goodsTotalUPrice,
            );
        $this->ajaxReturn(true,'message',$returnArr);
    }
}